#encoding:utf-8

import urllib2
import urllib
import os

#urllib 和 urllib2 的区别 :
#urllib 仅仅可以接收 url 能够用urlencode 进行编码

# urllib2 可以接收 设置了 header 的Request类
#一般将这两个搭配起来用
#模拟百度搜索
#https://www.baidu.com/s?wd=关键词

def baidu_search(params):
    url = 'http://www.baidu.com/s?'+ params

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
    }

    #创建请求对象
    req = urllib2.Request(url,headers=headers)
    res = urllib2.urlopen(req)
    # print res.read()
    dir = './'
    os.chdir(dir)
    file = res.read()
    open("baidu.html","wb").write(file)
    print "ok"
if __name__ == "__main__":
    kw = raw_input("请输入要查找的关键词:")
    params = {
        'wd':kw
    }
    #将字典转化成字符串
    params = urllib.urlencode(params)
    baidu_search(params)